package com.autumn.chat.util;

import java.nio.ByteBuffer;

public class ByteUtil {

    //System.arraycopy()方法
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length + bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }

    /**
    * Description: 类型 转 字节数组
    * @param num
    * @return: byte[]
    * @author: Shen_Yue
    * @Date: 17:40 2023/3/3
    */
    public static byte[] intToByte(int num) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (num >> 24);
        bytes[1] = (byte) (num >> 16);
        bytes[2] = (byte) (num >> 8);
        bytes[3] = (byte) num;
        return bytes;
    }

    /**
    * Description: short类型 转 字节数组
    * @param num
    * @return: byte[]
    * @author: Shen_Yue
    * @Date: 17:40 2023/3/3
    */
    public static byte[] shortToByte(short num) {
        byte[] bytes = new byte[2];
        bytes[0] = (byte) (num >> 8);
        bytes[1] = (byte) num;
        return bytes;
    }

    /**
    * Description: 字节数组截取
    * @param array 源数组
    * @param startIndex 开始的指针
    * @param endIndex 结束的指针
    * @return: byte[] 截取后的数组
    * @author: Shen_Yue
    * @Date: 18:11 2023/3/3
    */
    public static byte[] subArray(byte[] array, int startIndex, int endIndex) {
        if (startIndex < 0 || endIndex > array.length || startIndex > endIndex) {
            throw new IllegalArgumentException("数组越界");
        }
        int length = endIndex - startIndex + 1;
        byte[] subArray = new byte[length];
        System.arraycopy(array, startIndex, subArray, 0, length);
        return subArray;
    }
}
